import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";

//路由配置
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login/index.vue"),
  },
  {
    path: "/home",
    name: "home",
    redirect: "/welcome",
    meta: {
      auth: true,
    },
    component: () => import("@/views/Home/index.vue"),
    children: [
      {
        path: "/welcome",
        name: "welcome",
        meta: { auth: true },
        component: () => import("@/views/Home/Welcome.vue"),
      },
      {
        path: "/users",
        name: "users",
        component: () => import("@/views/Home/Users/index.vue"),
      },
      {
        path: "/rights",
        name: "rights",
        meta: {
          aa: ["权限管理", "权限列表"],
        },
        component: () => import("@/views/Home/Rights/rightList.vue"),
      },
      {
        path: "/roles",
        name: "roles",
        meta: {
          aa: ["权限管理", "角色列表"],
        },
        component: () => import("@/views/Home/Rights/roleList.vue"),
      },
      {
        path: "/categories",
        name: "categories",
        component: () => import("@/views/Home/Goods/goodsCate.vue"),
      },
      {
        path: "/params",
        name: "params",
        component: () => import("@/views/Home/Goods/goodsParams.vue"),
      },
      {
        path: "/goods",
        name: "goods",
        component: () => import("@/views/Home/Goods/goodsList.vue"),
      },
      {
        path: "/addgoods",
        name: "addgoods",
        component: () => import("@/views/Home/Goods/goodsAdd.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const flag = to.matched.some((item) => {
    return item.meta.auth;
  });

  //如果是flag为true，需要鉴权
  if (flag) {
    //再检测有没有token
    const token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      next({
        path: "/login",
      });
    }
  } else {
    next();
  }
});

export default router;
